package io.gitee.zhangbinhub.acp.cloud.resource.server.exceptions

import cn.dev33.satoken.exception.NotLoginException
import cn.dev33.satoken.exception.NotPermissionException
import cn.dev33.satoken.exception.SaTokenException
import cn.dev33.satoken.oauth2.exception.SaOAuth2Exception
import io.gitee.zhangbinhub.acp.boot.exceptions.AcpWebExceptionHandler
import io.gitee.zhangbinhub.acp.boot.exceptions.ErrorResult
import io.gitee.zhangbinhub.acp.boot.tools.PackageTools
import org.springframework.core.Ordered
import org.springframework.http.HttpStatus

class AcpCloudResourceServerWebExceptionHandler : AcpWebExceptionHandler {
    override fun getOrder(): Int = Ordered.LOWEST_PRECEDENCE - 1
    override fun identify(ex: Throwable?): Boolean = ex is SaTokenException
    override fun handle(ex: Throwable?): ErrorResult = when (ex) {
        is SaOAuth2Exception -> {
            PackageTools.buildErrorResult(HttpStatus.UNAUTHORIZED, "token 无效")
        }

        is NotLoginException -> {
            PackageTools.buildErrorResult(HttpStatus.UNAUTHORIZED, "token 无效")
        }

        is NotPermissionException -> {
            PackageTools.buildErrorResult(HttpStatus.FORBIDDEN, ex.message)
        }

        is SaTokenException -> {
            PackageTools.buildErrorResult(HttpStatus.UNAUTHORIZED, ex.message)
        }

        else -> {
            PackageTools.buildErrorResult(HttpStatus.INTERNAL_SERVER_ERROR, ex?.message)
        }
    }
}